package com.junmoo.www.auth.module.system.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.junmoo.www.auth.module.system.mapper.SysUserMapper;
import com.junmoo.www.entity.SysUser;
import com.junmoo.www.tool.Result;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;


@Service
@AllArgsConstructor
public class SysUserService {

    private final SysUserMapper sysUserMapper;

    private final PasswordEncoder passwordEncoder;
//
//    @Autowired
//    private JwtTokenUtil jwtTokenUtil;
//
//
//    private final static Map<String, VerificationCode> concurrentHashMap=new ConcurrentHashMap<>();

    public List<SysUser> findAll(){
        return sysUserMapper.selectList(new QueryWrapper<SysUser>());
    }

    private LambdaQueryWrapper<SysUser> queryByAnd(SysUser entity){
        return new LambdaQueryWrapper<SysUser>()
                .eq(entity.getId()!=null,SysUser::getId,entity.getId())
                .eq( StringUtils.hasText(entity.getUsername()),SysUser::getUsername,entity.getUsername())
                .eq( StringUtils.hasText(entity.getEmail()),SysUser::getEmail,entity.getEmail())
                .eq( StringUtils.hasText(entity.getMobile()),SysUser::getMobile,entity.getMobile());

    }

    private LambdaQueryWrapper<SysUser> queryByOr(SysUser entity){
        return new LambdaQueryWrapper<SysUser>()
                .eq(entity.getId()!=null,SysUser::getId,entity.getId())
                .or()
                .eq(StringUtils.hasText(entity.getUsername()),SysUser::getUsername,entity.getUsername())
                .or()
                .eq(StringUtils.hasText(entity.getEmail()), SysUser::getEmail,entity.getEmail())
                .or()
                .eq(StringUtils.hasText(entity.getMobile()), SysUser::getMobile,entity.getMobile());

    }

    public SysUser findOneByAnd(SysUser entity) {
        return sysUserMapper.selectOne( queryByAnd(entity) );
    }
    public List<SysUser> findByAnd(SysUser entity) {
        return sysUserMapper.selectList( queryByAnd(entity) );
    }

    public SysUser findOneByOr(SysUser entity) {
        return sysUserMapper.selectOne( queryByOr(entity) );
    }
    public List<SysUser> findByOr(SysUser entity) {
        return sysUserMapper.selectList( queryByOr(entity) );
    }

    public IPage<SysUser> page(SysUser search, int currentPage, int Pagesize,String sortField,String sortOrder) {
        Page<SysUser> page = new Page<>(currentPage , Pagesize);
        OrderItem orderItem = "asc".equalsIgnoreCase(sortOrder)?OrderItem.asc(sortField):OrderItem.desc(sortField);
        List<OrderItem> orders = Stream.of( orderItem ).collect(Collectors.toList());
        page.setOrders(orders);
        return sysUserMapper.selectPage( page, queryByOr(search) );
    }

    @Transactional
    public Result create(SysUser entity) {
        if(StringUtils.hasText(entity.getPassword())){
            entity.setPassword( passwordEncoder.encode(entity.getPassword()) );
        }
        if(StringUtils.hasText(entity.getUsername())){
            SysUser repoEntity = sysUserMapper.selectOne( queryByOr(
                    new SysUser()
                            .setUsername(entity.getUsername())
                            .setEmail(entity.getEmail())
                            .setMobile(entity.getMobile())
                    ) );
            if(repoEntity!=null) {
                return Result.error("用户名,手机号,邮箱已存在！！！");
            }
        }
        if(sysUserMapper.insert(entity)==0) {
            return Result.error("新建用户失败！！！");
        }
        return Result.success("success");
    }
//
//    @Transactional
//    public Result edit(SysUser entity) {
//        if(StringUtils.hasText(entity.getPassword()) ) {
//            entity.setPassword( passwordEncoder.encode(entity.getPassword()) );
//        }
//        if(entity.getUserId()==null ||entity.getUserId()==0 ){
//            return Result.error("无法修改，找不到用户！！！");
//        }
//
//        SysUser repoEntity = sysUserRepository.getOne(entity.getUserId());
//        if(repoEntity==null) {
//            return Result.error("无法修改，用户不存在！！！");
//        }
//        entity = BeanUtil.copyNullProperties(entity,repoEntity);
//        SysUser returnEntity=sysUserRepository.save(entity);
//        if(returnEntity==null) {
//            return Result.error("修改失败！！！");
//        }
//        return Result.success("success");
//    }
//
//
//    @Transactional
//    public Result deleteByIds(List<Number> ids) {
//        ids.removeAll(Collections.singleton(null));
//        if(CollectionUtils.isEmpty(ids)) {
//            return Result.error("error");
//        }
//        List<Long> list=ids.stream().map(id-> Long.valueOf(String.valueOf(id ))).collect(Collectors.toList());
//        sysUserRepository.deleteAll( sysUserRepository.findAllById(list) );
//        return Result.success("success");
//    }
//    @Transactional
//    public Result assignRole(Number userID , List<Number> roleIds) {
//        roleIds.removeAll(Collections.singleton(null));
//        String deleteSql = "delete from sys_user_role where user_id="+ userID;
//        String insertSql = "insert into sys_user_role (user_id,role_id) select "+userID+" as 'user_id',role_id from sys_role ";
//        StringBuilder insertSqlWhere = new StringBuilder(" where role_id in ( ");
//        roleIds.forEach(roleId->{
//            insertSqlWhere.append(roleId+", ");
//        });
//        insertSqlWhere.deleteCharAt(insertSqlWhere.lastIndexOf(","));
//        insertSql += insertSqlWhere.toString()+" ) ";
//        Query deleteQuery = entityManager.createNativeQuery(deleteSql);
//        Query insertQuery = entityManager.createNativeQuery(insertSql);
//        int deleteResult= deleteQuery.executeUpdate();
//        int insertResult= insertQuery.executeUpdate();
//        return Result.success("成功！！！！");
//    }
//    //获取验证码
//    public Result getVerificationCode(String mobile) {
//        OptionalInt optionalInt = new Random().ints(100000, 999999).limit(1).findFirst();
//        int intAsInt = optionalInt.getAsInt();
//        Date createTime = new Date();
//        Date expiration = new Date(createTime.getTime() + VerificationCode.getDuration());
//        VerificationCode verificationCode = new VerificationCode()
//                .setCode(intAsInt)
//                .setCreateTime(createTime)
//                .setExpiration(expiration );
//        concurrentHashMap.put(mobile,verificationCode);
//        String msg = "验证码是"+ intAsInt+",在"+ verificationCode.getDuration()/1000/60  + "分钟内有效！！";
//        return Result.success("success",msg);
//    }
//
//    public Result forgetPassword(Integer code, String mobile, String newPassword) {
//        SysUser repoEntity = sysUserRepository.findByMobile(mobile);
//        VerificationCode verificationCode = (VerificationCode)concurrentHashMap.get(mobile);
//        if(verificationCode ==null ){
//            return Result.error("验证码已失效！！！");
//        }
//        if(!verificationCode.isExpired(new Date())){
//            concurrentHashMap.remove(verificationCode);
//            return Result.error("验证码已过期！！！");
//        }
//        if(!verificationCode.isValid(code)){
//            concurrentHashMap.remove(verificationCode);
//            return Result.error("验证码已失效！！！");
//        }
//        SysUser entity = new SysUser().setPassword(newPassword).setMobile(mobile);
//        entity = BeanUtil.copyNullProperties(entity,repoEntity);
//        return edit(entity);
//    }
//
//    public Result editPassword(String oldPassword, String newPassword) {
//        if(oldPassword.equals(newPassword)) return Result.error("新旧密码相同，无需修改！！！");
//        SysUser sysUser = (SysUser)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        SysUser repoEntity = sysUserRepository.findByUsername(sysUser.getUsername());
//        if(!passwordEncoder.matches( oldPassword,repoEntity.getPassword())) return Result.error("原密码错误，无法修改！！！");
//        repoEntity = BeanUtil.copyNullProperties(new SysUser().setPassword(passwordEncoder.encode(newPassword)),repoEntity);
//        SysUser returnEntity = sysUserRepository.save(repoEntity);
//        if(returnEntity==null) {
//            return Result.error("修改失败！！！");
//        }
//        return Result.success("success");
//    }
//
//    public Result getToken(String username, String password) {
//        SysUser repoEntity = login(username);
//        if(repoEntity==null) Result.tokenExpired("token过期");
//        if(!passwordEncoder.matches( password,repoEntity.getPassword())) return Result.error("非法用户！！！");
//        // 得到用户角色
//        Set<SysRole> roles = repoEntity.getRoles();
//        Set<GrantedAuthority> authorities = new HashSet<>();
//        //权限集合，先放角色，再放权限
//        roles.forEach(role->{
//            authorities.add( new SimpleGrantedAuthority("ROLE_" + role.getRoleCode()) );
//            role.getResources().forEach(resource->{
//                authorities.add( new SimpleGrantedAuthority(resource.getResourceCode()) );
//            });
//        });
//        SecurityContextHolder.getContext().setAuthentication(new AppToken(repoEntity,password,authorities));
//        String token = jwtTokenUtil.generateToken(repoEntity);
//        return Result.success("success",token);
//    }
}
